package com.cj.cms.template;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cxf.common.util.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cj.cms.dao.security.ArticleDao;
import com.cj.cms.dao.security.ChannelDao;
import com.cj.cms.dao.security.TemplateDao;
import com.cj.cms.entity.Article;
import com.cj.cms.entity.Channel;
import com.cj.cms.entity.Template;
import com.cj.common.orm.Page;
import com.cj.common.utils.AppInfo;


@Service
@Transactional(readOnly = true)
public class PublishChannel {
	@Autowired
	private ArticleDao articleDao;
	@Autowired
	private TemplateDao templateDao;
	@Autowired
	private ChannelDao channelDao;
	
	public void publishChannel(Channel channel){
		if(channel == null || channel.getId() == null)
			return;
		channel = channelDao.load(channel.getId());
//		channel = channelDao.get(channel.getId());
		List<Long> templateIds = channel.getOtherTemplateIdsList();
		if(templateIds == null || templateIds.isEmpty())
			return;
		Criterion criterion = Restrictions.eq("channel.id", channel.getId());
		Page<Article> page = new Page<Article>(10,"isTop,modifyTime",Page.DESC + "," + Page.DESC);
//		if(channel.getArticleNum() != null)
//			page.setPageSize(channel.getArticleNum());
		page = articleDao.findByCriteria(page,criterion);
		Map<String,Object> context = new HashMap<String, Object>();
		context.put("entity", channel);
		context.put("articles", page.getResult());
		context.put("webSite", channel.getWebSite());
		context.put("children", channel.getSortChildren());
		String fileName = AppInfo.getAppPath() + channel.getWebSite().getTemplatePath() + "/";
		for(Long templateId : templateIds){
			Template template = templateDao.load(templateId);
			if(template == null || StringUtils.isEmpty(template.getPath()))
				continue;
			BuilderHtml.getInstance().runBuildContent(
					fileName + channel.getCode() + "_" + template.getCode() + ".shtml", 
					template.getPath(), context);
		}
	}
}
